<template>
  <div class="frame-page flex flex-column">
    <vxe-toolbar>
      <template #buttons>
        <Button @click="addForm()" color="primary">新增</Button>
        <Button @click="auditsForm('audits')">审核</Button>
        <Button @click="auditsForm('antiAudits')">反审核</Button>
      </template>
      <template #tools>
        <Search v-model.trim="params.filter" search-button-theme="h-btn-default"
                show-search-button class="w-360px ml-8px"
                placeholder="请输入单据编号/客户名称/制单人" @search="doSearch">
          <i class="h-icon-search"/>
        </Search>
      </template>
    </vxe-toolbar>
    <vxe-toolbar>
      <template #buttons>
        <div class="h-input-group">
          <span class="h-input-addon">供应商：</span>
          <Select :multiple="true" v-model="params.supplierIds" class="w-120px" keyName="id" titleName="name"
                  :datas="supplierList"/>
        </div>
        <div class="h-input-group">
          <span class="h-input-addon ml-8px">客户：</span>
          <Select v-model="params.customerIds" :filterable="true" :multiple="true" class="w-120px" keyName="id"
                  titleName="name"
                  :datas="customerList"/>
        </div>
        <div class="h-input-group">
          <span class="h-input-addon ml-8px">仓库：</span>
          <Select v-model="params.warehouseIds" :filterable="true" :multiple="true" class="w-120px" keyName="id"
                  titleName="name"
                  :datas="warehouseList"/>
        </div>
        <div class="h-input-group">
          <span class="h-input-addon ml-8px">产品：</span>
          <Select v-model="params.productIds" :filterable="true" :multiple="true" class="w-120px" keyName="id"
                  titleName="name" :datas="productList"/>
        </div>
        <div class="h-input-group">
          <span class="h-input-addon ml-8px">审核状态：</span>
          <Select v-model="params.state" class="w-120px" :datas="{未审核:'未审核',已审核:'已审核'}"/>
        </div>
        <div class="h-input-group">
          <span class="h-input-addon ml-8px">日期：</span>
          <DateRangePicker v-model="dateRange"></DateRangePicker>
        </div>
        <div class="h-input-group">
          <span class="h-input-addon ml-8px">业务类型：</span>
          <Select v-model="params.inboundType" class="w-120px" :datas="{盘盈入库:'盘盈入库',其他入库:'其他入库'}"/>
        </div>
      </template>
      <template #tools>
        <Button @click="doSearch" color="primary">查询</Button>
      </template>
    </vxe-toolbar>
    <div class="flex1">
      <vxe-table row-id="id"
                 ref="table"
                 height="auto"
                 :data="dataList"
                 highlight-hover-row
                 show-overflow
                 show-footer
                 :footer-method="footerMethod"
                 :row-config="{height: 48}"
                 :column-config="{resizable: true}"
                 :sort-config="{remote:true}"
                 :loading="loading">
        <vxe-column type="checkbox" width="40" align="center"/>
        <vxe-column title="操作" align="center" width="120">
          <template #default="{row}">
            <span v-if="!editable(row)" class="primary-color  text-hover ml-10px"
                  @click="addForm('look',row.id)">查看</span>
            <span v-if="editable(row)" class="primary-color  text-hover ml-10px"
                  @click="addForm('edit',row.id)">编辑</span>
            <span v-if="editable(row)" class="red-color  text-hover ml-10px" @click="doRemove(row)">删除</span>
          </template>
        </vxe-column>
        <vxe-column title="单据日期" field="inboundDate" align="center" width="130"/>
        <vxe-column title="单据编号" field="orderNo" width="200"/>
        <!--        <vxe-column title="单据来源" field="code" width="200"/>-->
        <vxe-column title="业务类型" field="inboundType" min-width="120"/>
        <vxe-column title="金额" field="totalAmount" width="120"/>
        <vxe-column title="供应商编号" field="supplierCode" width="120"/>
        <vxe-column title="供应商" field="supplierName" width="120"/>
        <vxe-column title="客户编码" field="customerCode" align="center" width="100"/>
        <vxe-column title="客户" field="customerName" align="center" width="100"/>
        <vxe-column title="数量" field="quantity" align="center" width="100"/>
        <vxe-column title="制单人" field="createdByName" align="center" width="100"/>
        <!--        <vxe-column title="打印次数" field="createDate" align="center" width="100"/>-->
        <vxe-column title="单据备注" field="remarks" align="center" width="100"/>
        <vxe-column title="审核状态" field="orderStatus" width="80"/>

      </vxe-table>
    </div>
    <div class="flex justify-between items-center pt-5px">
      <vxe-pager perfect @page-change="loadList(false)"
                 v-model:current-page="pagination.page"
                 v-model:page-size="pagination.pageSize"
                 :total="pagination.total"
                 :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'Total']">
        <template #left>
          <span class="mr-12px text-16px">总金额：{{ amountTotal }}元</span>
          <vxe-button @click="loadList(false)" type="text" size="mini" icon="h-icon-refresh"
                      :loading="loading"></vxe-button>
        </template>
      </vxe-pager>
    </div>
  </div>
</template>
<script>
import manba from "manba";
import OtherInbound from "@js/api/inventory/OtherInbound";
import {mapMutations} from "vuex";
import {confirm, loading, message} from "heyui.ext";
import Product from "@js/api/basic/Product";
import Warehouse from "@js/api/basic/Warehouse";
import Supplier from "@js/api/basic/Supplier";
import Customer from "@js/api/basic/Customer";

const startTime = manba().startOf(manba.MONTH).format("YYYY-MM-dd");
const endTime = manba().endOf(manba.DAY).format("YYYY-MM-dd");

export default {
  name: "OtherInboundList",
  data() {
    return {
      dataList: [],
      loading: false,
      amountTotal: 0,
      totalParams: {},
      pagination: {
        page: 1,
        pageSize: 20,
        total: 0
      },
      params: {
        productIds: [],
        warehouseIds: [],
        customerIds: [],
        supplierIds: [],
        filter: null,
        state: null,
        sortCol: null,
        sort: null,
        inboundType: null
      },
      dateRange: {
        start: manba(startTime).format("YYYY-MM-dd"),
        end: manba(endTime).format("YYYY-MM-dd")
      },
      supplierList: [],
      warehouseList: [],
      customerList: [],
      productList: []
    }
  },
  computed: {
    queryParams() {
      return Object.assign(this.params, {
        page: this.pagination.page,
        pageSize: this.pagination.pageSize,
        start: this.dateRange.start,
        end: this.dateRange.end,
      })
    },
  },
  methods: {
    ...mapMutations(['pushTab']),
    addForm(type = 'add', otherInboundId = null) {
      console.log(type, otherInboundId);
      this.pushTab({
        key: 'OtherInboundForm',
        title: type === 'edit' ? '编辑其他入库单' : type === 'look' ? '查看其他入库单' : '新增其他入库单',
        params: {type: type, otherInboundId: otherInboundId}
      });
    },
    footerMethod({columns, data}) {
      let sums = [];
      let num = 0;
      columns.forEach((column) => {
        if (column.property && ['totalAmount'].includes(column.property)) {
          let total = 0;
          data.forEach((row) => {
            let rd = row[column.property];
            if (rd) {
              total += Number(rd || 0);
            }
          });
          sums.push(total.toFixed(2));
        }
        if (column.property && ['quantity'].includes(column.property)) {
          let total = 0;
          data.forEach((row) => {
            let rd = row[column.property];
            if (rd) {
              total += Number(rd || 0);
            }
          });
          num = total;
        }
      })
      sums.push("", "", "", "", num);
      return [["", "合计", "", "", ""].concat(sums)];
    },
    doSearch() {
      this.pagination.page = 1;
      this.loadList();
    },
    loadList(type = true) {
      this.loading = true;
      const params = JSON.parse(JSON.stringify(this.queryParams));
      params.productIds = params.productIds.join(",");
      params.warehouseIds = params.warehouseIds.join(",");
      params.supplierIds = params.supplierIds.join(",");
      params.customerIds = params.customerIds.join(",");
      OtherInbound.list(params).then(({data: {results, total}}) => {
        this.dataList = results || [];
        this.pagination.total = total;
        let amountTotal = 0;
        this.dataList.forEach(item => {
          amountTotal += Number(item.totalAmount);
        });
        this.amountTotal = amountTotal;
      }).finally(() => this.loading = false);
    },
    auditsForm(type) {
      const selectRecords = this.$refs.table.getCheckboxRecords();
      if (!selectRecords || selectRecords.length === 0) {
        message.warn("请选择要操作的数据~");
        return;
      }
      if (type === "audits") {
        const filterRecords = selectRecords.filter(item => item.orderStatus === "未审核");
        if (!filterRecords || filterRecords.length === 0) {
          message.warn("请选择状态为未审核的数据，进行审核~");
          return;
        }
        const ids = filterRecords.map(item => {
          return item.id
        });
        const params = {
          ids: ids.join(','),
          type: "AUDITS",
        };
        console.info(filterRecords, ids);
        loading("审核中....");
        OtherInbound.approves(params)
            .then((success) => {
              if (success) {
                message("审核成功~");
                this.$refs.table.clearCheckboxRow();
                this.loadList();
              }
            })
            .finally(() => loading.close());
        return;
      }
      if (type === "antiAudits") {
        console.info("selectRecords:", selectRecords);
        const filterRecords = selectRecords.filter(item => item.orderStatus === "已审核");
        if (!filterRecords || filterRecords.length === 0) {
          message.warn("请选择状态为已审核的数据，进行审核~");
          return;
        }
        const ids = filterRecords.map(item => {
          return item.id
        });
        const params = {
          ids: ids.join(','),
          type: "ANTI_AUDIT",
        };
        console.info(filterRecords, ids);
        loading("反审核中....");
        OtherInbound.approves(params)
            .then((success) => {
              if (success) {
                message("反审核成功~");
                this.$refs.table.clearCheckboxRow();
                this.loadList();
              }
            })
            .finally(() => loading.close());
      }
    },
    doRemove({id}) {
      confirm({
        title: "系统提示",
        content: `是否删除当前数据?`,
        onConfirm: () => {
          OtherInbound.delete(id).then(({data}) => {
            console.log(data);
            message.success("操作成功～");
            this.loadList();
          });
        },
      });
    },
    editable(row) {
      return ['未审核'].includes(row.orderStatus);
    },
    loadDict(callback) {
      loading("加载中....");
      Promise.all([Product.select(), Warehouse.select(), Supplier.select(), Customer.select()])
          .then((results) => {
            this.productList = results[0].data || [];
            this.warehouseList = results[1].data || [];
            this.supplierList = results[2].data || [];
            this.customerList = results[3].data || [];
            if (callback) {
              callback();
            }
          })
          .finally(() => loading.close());
    },
  },
  created() {
    this.loadDict();
    this.loadList();
  }
}
</script>
